const express = require('express')
const md5 = require('md5-node')
const chinaTime = require('china-time')

const User = require('../db/user.js')
const UserInfo = require('../db/userInfo.js')
const cookieCheck = require('../cookieCheck.js')

const router = express.Router()

/* -------	get 请求路由  ------- */

/**
 * 获取所有用户的用户信息
 */
router.get('/getAllUserInfo',function(req,res){
	
	cookieCheck(req.cookies).then(user => {
		
		// console.log(user.privilegeLevel)
		if(user.privilegeLevel >= 10){
			UserInfo.find(function(err,data){
				if(err){
					console.log(err)
				}else{
					res.json(data)
				}
			})
		}else{
			res.json({msg:'权限不足'})
		}
	}).catch(msg => {
		console.log(msg)
	})
})

/**
 * 获取所有用户的账号信息
 */
router.get('/getAllUser',function(req,res){
	User.find((err,data) => {
		if(err){
			console.log(err)
		}else{
			res.json(data)
		}
	})
})

/**
 * 退出账号请求
 */
router.get('/logout',(req,res) => {
	req.session.user = undefined
	res.clearCookie('account')
	res.clearCookie('pw')
	res.status('200').json('退出成功')
})

/**
 * 验证cookie
 */
router.get('/cookie',(req,res) => {
	cookieCheck(req.cookies).then(user => {
		// console.log('验证成功!')
	}).catch(msg => {
		console.log(msg)
	})
	
})


/* ------ post 请求路由 ------- */

/**
 * 处理注册请求
 */
router.post('/register',function(req,res){
	// console.log('收到注册请求:'+chinaTime())
	User.findOne({
		account: md5(req.body.QQ)
	})
	.then(function(user){
		if(user){
			res.status('200').json({
				error_code:200,
				message:'QQ号已注册'
			})
		}else{
			let QQ = req.body.QQ
			let pw = req.body.password
			let UserObj = {}
			UserObj.account = md5(QQ)
			UserObj.nickName = req.body.nickName
			if(!pw){
				//不输入密码，使用默认密码
				UserObj.password = md5(md5('123456')+'hey!')
				pw = '123456'
			}else{
				UserObj.password = md5(md5(pw)+'hey!')
			}
			
			let UserInfoObj = {}
			UserInfoObj.account = md5(QQ)
			UserInfoObj.QQ = req.body.QQ
			UserInfoObj.nickName = req.body.nickName
			UserInfoObj.sex = req.body.sex
			UserInfoObj.year = req.body.year
			UserInfoObj.college = req.body.college
			UserInfoObj.major = req.body.major
			UserInfoObj.department = req.body.department
			UserInfoObj.hobbies = req.body.hobbies
			UserInfoObj.expect = req.body.expect
			
			const newUser = new User(UserObj)
			newUser.save()
			const newUserInfo = new UserInfo(UserInfoObj)
			newUserInfo.save()
			req.session.user = newUser
			res.cookie('account', UserObj.account, {maxAge:172800000})
			res.cookie('pw', md5(pw), {maxAge:172800000})
			
			res.status('200').json({
				message:'register success'
			})
		}
	})
	.catch(err =>{
		console.log(err)
		res.status('500').json({
			message:err
		})
	})
	
})

/**
 * 处理登录请求
 */
router.post('/login',function(req,res){
	// console.log('login'+ req.body.QQ)
	let account = md5(req.body.QQ)
	let pw = md5(md5(req.body.password)+'hey!')	
	User.findOne({
		account:account,
		password:pw
	})
	.then(user => {
		if(!user){
			res.json({message:'账号或密码不正确'})
		}else{
			// console.log('登录成功:'+ user.account)
			req.session.user = user
			res.cookie('account', user.account, {maxAge:172800000})
			res.cookie('pw', md5(req.body.password), {maxAge:172800000})
			res.status('200').json(user)
		}
	})
})

/**
 * cookie快速登录
 */
router.post('/autoLogin',(req,res) => {
	// console.log('auto cookie:'+req.cookies.account)
	// console.log('auto cookie:'+req.cookies.pw)
	if(req.cookies == undefined){
		res.status('200').json({message:'cookie为空'})
		return
	}
	cookieCheck(req.cookies).then(user => {
		req.session.user = user
		res.cookie('account', user.account, {maxAge:172800000})
		res.cookie('pw', req.cookies.pw, {maxAge:172800000})
		res.status('200').json(user)
	}).catch(msg => {
		console.log(msg)
	})
})

/**
 * 处理查询请求
 */
router.post('/search',(req,res) => {
	if(req.body.message == ''){
		res.status('200').json({message:'输入为空'})
		return
	}
	const message = req.body.message
	const deNum = /\D+/
	if(deNum.test(message)){
		UserInfo.find({$or:[
			{nickName:req.body.message},
		]})
		.then(user => {
			if(JSON.stringify(user)=="[]"){
				// console.log('用户不存在')
				res.status('200').json({message:'用户不存在'})
			}else{
				res.status('200').json(user)
			}
		})
		return
	}
	UserInfo.find({$or:[
			{QQ: req.body.message},
			{nickName:req.body.message},
		
	]})
	.then(user => {
		if(JSON.stringify(user)=="[]"){
			// console.log('用户不存在')
			res.status('200').json({message:'用户不存在'})
		}else{
			res.status('200').json(user)
		}
	})
	
})

/**
 * 处理修改成员信息请求
 */
router.post('/updateOne',(req,res) =>{
	let QQsrc = req.body.QQsrc
	let acc = md5(QQsrc)
	let targetUser = req.body
	UserInfo.updateOne({account:acc},
	{$set:
		{account:md5(targetUser.QQ),
		QQ:targetUser.QQ,
		nickName:targetUser.nickName,
		year:targetUser.year,
		college:targetUser.college,
		major:targetUser.major,
		department:targetUser.department
		}},
	(err,res) =>{
		if(err){
			console.log(err)
		}
	})
	User.updateOne({account:acc},
	{$set:
	{account:md5(targetUser.QQ),
	nickName:targetUser.CN
	}},
	(err,succ) =>{
		if(err){
			console.log(err)
		}
	})
	.then( ()=>{
		res.status('200').json({state:200,message:"修改成功"})
	})
	
})

/**
 * 处理删除成员请求
 */
router.post('/deleteOne',(req,res) => {
	const acc = md5(req.body.QQ)
		User.deleteOne({account:acc}, (err)=>{
			if(err){
				console.log('User删除失败')
				console.log(err)
			}else{
				// console.log('User删除成功')
			}
		})
		UserInfo.deleteOne({account:acc}, (err)=>{
			if(err){
				console.log('UserInfo删除失败')
				console.log(err)
			}else{
				res.status('200').json({state:200,message:"删除成功"})
			}
		})

})

module.exports = router